# 导入requests包
import requests
import json
from http.server import HTTPServer
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer, BaseHTTPRequestHandler
import http.client
import json
from icecream import ic
import time

def get_time():
    return str(time.time())[:10]
    
def get_token():
    url = "https://auth-box.inspurcloud.cn/auth/realms/picp/protocol/openid-connect/token"
    data = {"grant_type":"password",
    "username":"inspurtest01",
    "password":"opOP@123?",
    "client_id":"bss-client",
    "response_type": "code id_token"}
    res = requests.post(url=url, data = data)#这里传入的data,是body里面的数据。params是拼接url时的参数
    return json.loads(res.text)['access_token']

def add_template(body, token): 
    body['timestamp'] = get_time()
    body['nonce'] = body['timestamp']
    conn = http.client.HTTPSConnection("service-box.inspurcloud.cn")
    payload = json.dumps(body)
    headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer {}'.format(token)
    }
    conn.request("POST", "/regionsvc-region-box/mps/openapi/v1/transcode-templates", payload, headers)
    res = conn.getresponse()
    data = res.read()
    return data.decode("utf-8")

def delete_template(token, id):
    timestamp = get_time()
    conn = http.client.HTTPSConnection("service-box.inspurcloud.cn")
    payload = ''
    headers = {'Authorization': 'Bearer {}'.format(token)}
    url = "https://service-box.inspurcloud.cn/regionsvc-region-box/mps/openapi/v1/transcode-templates/{}?nonce={}&timestamp={}".format(id, timestamp, timestamp)
    # ic(url)
    # ic(token)
    conn.request("DELETE", url, payload, headers)
    res = conn.getresponse()
    data = res.read()
    return data.decode("utf-8")

class resquest_handler(BaseHTTPRequestHandler):
    def do_POST(self):
        # 获取并解析出参数
        command = self.path
        datas = self.rfile.read(int(self.headers['content-length']))
        parameters = json.loads(datas.decode())
        # ic(parameters)
        if command.startswith('/alter_template'):
            token = get_token()
            # 删除原模板
            result1 = delete_template(token, parameters['id'])
            ic(result1)
            result1 = json.loads(result1)['message']
            # 增加模板
            result2 = add_template(parameters['data'], token)
            result2 = json.loads(result2)
            result = result2.copy()
            result2 = result2['message']
            result['message'] = '修改失败'
            if result1 == '删除成功' and result2 == '新增成功':
                result['message'] = '修改成功'
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(result).encode())


if __name__ == '__main__':
    server_address = ('0.0.0.0', 8120)
    httpd = HTTPServer(server_address, resquest_handler)
    print("Starting server, listen at: %s:%s" % server_address)
    httpd.serve_forever()